﻿using AntMovement.Comm.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AntMovement.Comm
{
    public class AntProtocol
    {
        private byte[] _sessionHandle;
        public AntProtocol()
        {
            _sessionHandle = new byte[4];
        }

        public void SetHandle(byte[] session)
        {
            _sessionHandle = session;
        }

        public byte[] Deserialize(IList<byte> data)
        {
            if (data[10] == 0x60)
            {
                return data.ToArray();
            }
            return data.Skip(11).ToArray();
        }

        public byte[] Serialize(IList<byte> data)
        {
            List<byte> result = new List<byte>(new byte[] { 0x58, 0x4C });
            result.AddRange(_sessionHandle);
            int command_length = data.Count + 2;
            result.Add((byte)command_length);
            result.Add((byte)(command_length >> 8));
            result.Add(0);
            result.Add(0);
            result.AddRange(data);
            return result.ToArray();
        }

        public bool Verify(IList<byte> bytes)
        {
            if (bytes.Count < 6)
            {
                System.Threading.Thread.Sleep(2);
                return false;
            }
            int length = (bytes[6] + (bytes[7] << 8)) + 8;
            if (length < bytes.Count)
            {
                return false;
            }
            if (bytes[8] != 0)
            {
                throw new AntErrorException(GetStatusCode(bytes[8]));
            }
            return true;
        }

        private string GetStatusCode(byte code)
        {
            switch (code)
            {
                case 0x01: return "注册失败";
                case 0x02: return "未注册";
                case 0x03: return "不存在标签";
                case 0x04: return "报文长度不对";
                case 0x05: return "解析标签异常";
                case 0x06: return "标签长度与数据长度对应不上";
                case 0x07: return "写入失败";
                case 0x08: return "解析值异常";
                case 0x09: return "不支持结构体数组";
                case 0x0A: return "未实现该数据类型";
                case 0x0B: return "Already in requested mode/state";
                case 0x0C: return "Object state conflict";
                case 0x0D: return "Object already exists";
                case 0x0E: return "Attribute not settable";
                case 0x0F: return "Privilege violation";
                case 0x10: return "Device state conflict";
                case 0x11: return "Reply data too large";
                case 0x12: return "Fragmentation of a primitive value";
                case 0x13: return "Not enough data";
                case 0x14: return "Attribute not supported";
                case 0x15: return "Too much data";
                default: return "未知异常";
            }
        }
    }
}
